#coding:utf-8
from geventwebsocket.handler import WebSocketHandler
from gevent.pywsgi import WSGIServer
from flask import Flask, request, render_template
import resolve
import threading
import smartQQ.QQ_class
global observers
msgsrv = resolve.MessageServer()
app = Flask(__name__)

@app.route('/message/')
def message():
    if request.environ.get('wsgi.websocket'):
        ws = request.environ['wsgi.websocket']
        print request.environ
        msgsrv.observers.append(ws)#所有在线用户
        webQQ._set_observer(msgsrv.observers)
        while True:
            try:
                message = ws.receive()
                if message != None:
                    msgsrv._poll_to_all_user(message)
                    #print 'QQ:',Login
                    #if Login:
                    webQQ.MsgTask(0,0,message)
                    print message
                else:
                    break
            except:
                continue
    return "Connected!"
if __name__ == '__main__':

    webQQ = smartQQ.QQ_class.WebQQ()
    http_server = WSGIServer(('0.0.0.0',5000), app, handler_class=WebSocketHandler)

    #WebSocketLoop = threading.Thread(target=http_server.serve_forever)
    #WebSocketLoop.start()
    QQ_Loop = threading.Thread(target=webQQ.run)

    QQ_Loop.start()
    http_server.serve_forever()


